//
//  QSAddVisitViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/30.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSAddVisitViewController.h"
#import "QSAddVisitFirstCell.h"
#import "QSAddVisitSecondCell.h"
#import "QSAddVisitSuccessViewController.h"
#import "QSVisitInterFace.h"
#import "QSOSSUploadHelper.h"
#import "QSProblemReportFirstCell.h"
#import "QSProblemReprotInterface.h"
#import "QSProblemListModel.h"
@interface QSAddVisitViewController (){
}
/** 提交问题Button*/
@property (nonatomic, strong)UIButton *submitButton;
@property (nonatomic, strong)UIView *footerView;
@property (nonatomic, strong)UIView *clearView;
@property (nonatomic, strong)UIButton *addProblemButton;

@property (nonatomic, strong)NSMutableArray *addProblemArr;//问题模型的数组
@property (nonatomic, strong)NSString *evType;
@property (nonatomic, strong)NSString *evTime;
@property (nonatomic, strong)NSString *evFollow;
@property (nonatomic, strong)NSString *evRemark;
@property (nonatomic, strong)NSString *evPic;
@property (nonatomic, strong)NSMutableArray *problemList;//装有字典的问题数组

@property (nonatomic, strong)NSArray *problemTypeArr;//装有问题类型的数组

@property (nonatomic, copy)NSArray *photoArray;
@property (nonatomic, copy)NSArray *imageUrlArr;
@property (nonatomic, assign) CGFloat itemWH;

@end

static NSString *kVisitFirstCell = @"VisitFirstCell";
static NSString *kVisitSecoundCell = @"VisitSecoundCell";
static NSString *problemFirstcell = @"ProblemFirstcell";
@implementation QSAddVisitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupForDismissKeyboard];//键盘回收
//    [self registerForKeyboardNotifications];//注册键盘通知（上移）
    
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"新增走访";
    self.tableView.frame = CGRectMake(10, 0, kScreenWidth - 20, kScreenHeight - kNavgationBarHeight - kRealValue(78));
    self.tableView.tableFooterView = self.footerView;
    [self.tableView registerNib:[UINib nibWithNibName:@"QSAddVisitFirstCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kVisitFirstCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"QSAddVisitSecondCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kVisitSecoundCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"QSProblemReportFirstCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:problemFirstcell];
    [self configSubView];
    self.pNum = -1;
    [self getProblemType];//请求问题类型列表
    
    if (self.evSignId) {//从签到过来点返回直接返回首页
        UIBarButtonItem *backBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_navigation_back"] target:self action:@selector(handleBackHome:)];        
        self.navigationItem.leftBarButtonItem = backBtn;
    }
}

- (void)configSubView{
    [self.view addSubview:self.submitButton];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(24));
        make.right.equalTo(self.view).offset(- kRealValue(24));
        make.bottom.equalTo(self.view).offset(- kRealValue(24));
        make.height.offset(44);
    }];
    self.itemWH = kRealValue(kScreenWidth - 28 - 20 - 9) / 4;
}

#pragma mark - **************** UITableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2 + _addProblemArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        QSAddVisitFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:kVisitFirstCell forIndexPath:indexPath];
        if (self.companyName) {
            [cell.selectCompanyButton setTitle:self.companyName forState:UIControlStateNormal];
            cell.selectCompanyButton.userInteractionEnabled = NO;
        }
        if (_companyModelList.count) {
            cell.companyArr = _companyModelList;
        }
        cell.addVisitDidSelectCompanyBlock = ^(NSString * _Nonnull companyKey) {
            NSLog(@"%@", companyKey);
            self.companyKey = companyKey;
        };
        cell.addVisitDidSelectContactBlock = ^(NSString * _Nonnull contactName) {
            NSLog(@"%@", contactName);
            self.evFollow = contactName;
        };
        cell.addVisitDidSelectVistTypeBlock = ^(NSString * _Nonnull visitType) {
            DLog(@"%@", visitType);
            self.evType = visitType;
        };
        cell.addVisitDidSelectDateBlock = ^(NSString * _Nonnull Date) {
            DLog(@"%@", Date);
            self.evTime = Date;
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if(indexPath.row == 1){
        QSAddVisitSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:kVisitSecoundCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.addVisitDidRemarkEditFinish = ^(NSString * _Nonnull remark) {
            NSLog(@"%@", remark);
            self.evRemark = remark;
        };
        cell.addVisitDidClickSelectImages = ^(NSArray<UIImage *> * _Nonnull selectPhotos) {
            self.photoArray = selectPhotos;
//            NSLog(@"%@", _photoArray);
            [self.tableView reloadData];
        };
        return cell;
    }else{
//        NSString*cellID = [NSString stringWithFormat:@"%zd",indexPath.row - 2];
        UINib *cellNib;
        cellNib = [UINib nibWithNibName:@"QSProblemReportFirstCell" bundle:nil];
        QSProblemReportFirstCell *cell = [cellNib instantiateWithOwner:nil options:nil][0];
//        if (!cell) {
//            cell = (QSProblemReportFirstCell *)[[[NSBundle mainBundle]  loadNibNamed:@"QSProblemReportFirstCell" owner:self options:nil]  objectAtIndex:0];
//            [cell setValue:cellID forKey:@"reuseIdentifier"];
//        }else{
////            [cell initView];
//        }
        cell.type = 1;//新增走访的Type
        cell.problemTypeArr = self.problemTypeArr;
        QSProblemListModel *model = self.addProblemArr[indexPath.row -2];
        cell.model = model;
        WeakSelf(weakSelf);
        if (_problemTypeArr.count) {
            cell.problemTypeArr = _problemTypeArr;
            cell.didSelectProblemTypeFinish = ^(NSString * _Nonnull ptName, NSString * _Nonnull ptId) {
//                self.typeId = ptId;
                NSLog(@"%@, %@", ptName, ptId);
                model.typeId = ptId;
            };
        }
        cell.didTitleInputFinish = ^(NSString * _Nonnull problemTitle) {
            NSLog(@"%@", problemTitle);
            model.title = problemTitle;
        };
        cell.didDescriptionInputFinish = ^(NSString * _Nonnull problemDescription) {
            NSLog(@"%@", problemDescription);
//            self.info = problemDescription;
            model.info = problemDescription;
        };
        cell.didSelectImageFinish = ^(NSArray * _Nonnull imageArr) {
//            self.imageArr = imageArr;
            NSLog(@"%@", imageArr);
//            model.picArr = imageArr.mutableCopy;
        };
        cell.didDeleteProblemBlock = ^(UIButton * _Nonnull deleteButton) {
            
            weakSelf.pNum --;//2
            [weakSelf.addProblemArr removeObjectAtIndex:indexPath.row - 2];
            [weakSelf.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            NSLog(@"%ld个",  self.addProblemArr.count);
            [weakSelf.tableView reloadData];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return kRealValue(260 + 10);//cell间距
    }else if(indexPath.row == 1){
        if (_photoArray.count >= 0 && _photoArray.count <= 3) {
            return kRealValue(86 + 20) + _itemWH;
        }else if (_photoArray.count >= 4 && _photoArray.count <= 7 ) {
            return kRealValue(86 + 20) + _itemWH *2 + 3;
        }
        else{
            return kRealValue(86 + 20) + _itemWH *3 + 6;
        }
    }else{
        //问题提交cel高度
        return kRealValue(374 + 10);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark  - Lazy Load
- (UIButton *)submitButton{
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitButton.layer.cornerRadius = 22;
        _submitButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
        [_submitButton setTitle:@"提交走访记录" forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
        _submitButton.titleLabel.font = [UIFont QSFontOfSize16];
        [_submitButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitButton;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] init];
        _footerView.size = CGSizeMake(0, kRealValue(44));
        _footerView.layer.cornerRadius = 5;
        _footerView.backgroundColor = [UIColor clearColor];
        
        self.clearView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 20, kRealValue(10))];
        _clearView.backgroundColor = [UIColor clearColor];
        [self.footerView addSubview:self.clearView];
        
        self.addProblemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.addProblemButton.frame = CGRectMake(0, 10, kScreenWidth - 20, 34);
        self.addProblemButton.backgroundColor = [UIColor colorWithRed:174 / 255.0f green:212 / 255.0f blue:242 / 255.0f alpha:1];
        self.addProblemButton.layer.cornerRadius = 5;
        [self.addProblemButton setTitle:@"快捷提交问题" forState:UIControlStateNormal];
        self.addProblemButton.titleLabel.font = [UIFont QSFontOfSize14];
        [self.addProblemButton setTitleColor:[UIColor colorWithHexString:@"#128BEC"] forState:UIControlStateNormal];
        [self.addProblemButton addTarget:self action:@selector(addProblemAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:self.addProblemButton];
    }
    return _footerView;
}

- (NSMutableArray *)addProblemArr{
    if (!_addProblemArr) {
        _addProblemArr = [NSMutableArray array];
    }
    return _addProblemArr;
}

- (NSMutableArray *)problemList{
    if (!_problemList) {
        _problemList = [NSMutableArray array];
    }
    return _problemList;
}

- (void)submitAction:(UIButton *)sender{
    if (self.companyKey.length <= 0) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请选择企业"];
        return;
    }
    if (self.evFollow.length <= 0) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请输入联系人"];
        return;
    }
    if (self.evType.length <= 0) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请选择走访方式"];
        return;
    }
    //快捷提交问题判断
    NSLog(@"--%ld", (long)_pNum);
    
    if (self.addProblemArr.count) {
        for (QSProblemListModel *model in self.addProblemArr) {
            if (!model.typeId) {
                [QSAppKeyWindow showAutoHideHudWithText:@"请选择问题类型"];
                return;
            }
            if (!model.title) {
                [QSAppKeyWindow showAutoHideHudWithText:@"请输入问题标题"];
                return;
            }
            if (!model.info) {
                [QSAppKeyWindow showAutoHideHudWithText:@"请输入问题描述"];
                return;
            }
        }
        for (QSProblemListModel *model in self.addProblemArr) {
            model.companyKey = self.companyKey;
            self.view.userInteractionEnabled = NO;
            [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
            if (model.picArr.count) {
                //传model里图片
                    [QSOSSUploadHelper asyncUploadFilesToOSS:model.picArr.copy complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
                        if (!error) {
                            NSArray *urlArr = names;
                            NSString *picStr = [self conversionStrWithArray:urlArr];
                            NSLog(@"拼装的字符串为--%@", picStr);
                            NSDictionary *dic = @{@"companyKey" : model.companyKey,
                                                  @"info" : model.info,
                                                  @"title" : model.title,
                                                  @"typeId" : model.typeId,
                                                  @"pic" : picStr
                            };
                            [self.problemList addObject:dic];
//                            dispatch_semaphore_signal(semaphore);
                        }else{
                            [QSAppKeyWindow hideHud];
                            [QSAppKeyWindow showAutoHideHudWithText:@"阿里云传输遇到阻塞"];
//                            dispatch_semaphore_signal(semaphore);
                        }
                    }];
//                    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                    NSLog(@"第一个请求");
//                });

                }else{
                    //没有图片不穿pic字段
                    NSDictionary *dic = @{@"companyKey" : model.companyKey,
                                          @"info" : model.info,
                                          @"title" : model.title,
                                          @"typeId" : model.typeId
                    };
                    [self.problemList addObject:dic];
                }
            }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"发送的问题数组%@", self.problemList);
            [self isNeedSendOssAction];//阿里云上传操作
        });
    }else{
        self.view.userInteractionEnabled = NO;
        [self isNeedSendOssAction];
    }
}

- (void)handleBackHome:(UIBarButtonItem *)sender{
    [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
}
//判断添加走访是否添加了图片 有则传阿里云 再提交 没有直接提交
- (void)isNeedSendOssAction{
    if (self.photoArray.count!= 0) {
        [QSOSSUploadHelper asyncUploadFilesToOSS:self.photoArray complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
            if (!error) {
                self.imageUrlArr = names;
                [self addActionWithUrlArr:self.imageUrlArr];
            }else{
                [QSAppKeyWindow hideHud];
                [QSAppKeyWindow showAutoHideHudWithText:@"阿里云传输遇到阻塞"];
            }
        }];
    }else{
        //直接提交
        [self addActionWithUrlArr:self.imageUrlArr];
    }
}

//数组解析为字符串 并上传
- (void)addActionWithUrlArr:(NSArray *)urlArr{
    if (urlArr.count) {
        _evPic = [self conversionStrWithArray:urlArr];
        NSLog(@"%@", _evPic);
    }
    if (!_evTime) {
        NSString *curruntDate = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970] *1000];
        _evTime = curruntDate;
    }
    [QSAppKeyWindow showIndeterminateHudWithText:@"正在提交"];
    [QSVisitInterFace postAddNewVisitWithEvCompanyKey:_companyKey EvType:_evType EvTime:_evTime EvFollow:_evFollow EvRemark:_evRemark EvPic:_evPic EvSignId:_evSignId ProblemList:_problemList AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        self.view.userInteractionEnabled = YES;
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (self.evSignId) {//签到过来的直接跳首页
                [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
                [QSAppKeyWindow showAutoHideHudWithText:@"提交成功"];
            }else{
                QSAddVisitSuccessViewController *vc = [QSAddVisitSuccessViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }];
}

- (void)addProblemAction:(UIButton *)sender{
    if (_pNum >= 2) {
        [QSAppKeyWindow showAutoHideHudWithText:@"最多添加3条数据"];
        return;
    }
    _pNum ++;
    NSString *valueStr = nil;
    QSProblemListModel *model = [QSProblemListModel new];
    model.index = _pNum;
    model.companyKey = self.companyKey;
    model.info = valueStr;
    model.title = valueStr;
    model.pic = valueStr;
    model.typeId = valueStr;
    model.picArr = [NSMutableArray array];
    [self.addProblemArr addObject:model];
    NSLog(@"添加了%lu个", (unsigned long)self.addProblemArr.count);
    [self.tableView reloadData];
}
//把数组里的拆分并拼接为以逗号分隔的一整个字符串
- (NSString *)conversionStrWithArray:(NSArray *)urlArr{
    NSString *urlStr;
    if (urlArr.count) {
        for (int i = 0; i < urlArr.count; i++) {
            NSString *feedImage = urlArr[i];
            if (i == 0) {
                urlStr = feedImage;
            } else {
                urlStr = [NSString stringWithFormat:@"%@,%@",urlStr,feedImage];
            }
        }
    }
    return urlStr;
}

#pragma mark - Request
- (void)getProblemType{
    [QSAppKeyWindow showIndeterminateHudWithText:@""];
    [QSProblemReprotInterface getApiProblemTypeListWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSArray * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.problemTypeArr = result;
        }
    }];
}

@end
